//
//  FHComposeViewController.swift
//  WeiBo
//
//  Created by qfh on 16/7/18.
//  Copyright © 2016年 qiufuhe. All rights reserved.
//

import UIKit

import SVProgressHUD

class FHComposeViewController: UIViewController {
    
   
 /// titleView
    
    private lazy var titleLabel: UILabel = {
    
        let label = UILabel(textColor: UIColor.grayColor(), size: 17)
    
        
        label.numberOfLines = 0
        
        label.textAlignment = .Center
        
        if let name = FHUserAccessViewModel.sharedUserAccessViewModel.userAccess?.name {
            
            let title = "发微博\n\(name)"
            
            let attributeStr = NSMutableAttributedString(string: title)
            
            let range = (title as NSString).rangeOfString(name)
            
            attributeStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
            
            
            label.attributedText = attributeStr
            
        
        } else {
        
            label.text = "发微博"
        }
    
    
    
        label.sizeToFit()
        
        return label
    
    }()
    
    /// 左边自定义button
    private lazy var rightButton: UIButton = {
    
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        button.setTitle("发送", forState: .Normal)
        
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        button.size = CGSize(width: 45, height: 30)
        
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        
        
    
    
        return button
    }()
    
    /// texView
    private lazy var textView: FHTextView = {
    
        let view = FHTextView()
        
        view.delegate = self
        
        view.font = UIFont.systemFontOfSize(15)
        
        view.alwaysBounceVertical = true
        
        view.placeHolder = "别低头,绿帽会掉~别低头,绿帽会掉~别低头,绿帽会掉~别低头"
        return view
    }()
    
    /// 自定义表情键盘
    private lazy var keyBoard: FHEmoticonKeyBoard = {
        
        let board = FHEmoticonKeyBoard()
        
        board.size = CGSize(width: ScreenWidth, height: 216)
        
        return board
        
    }()
    
    /// 图片视图
    private lazy var pictureView: FHComposePIctureView = FHComposePIctureView()
    /// 底部toobar  视图
    private lazy var composeToolBar: FHComposeToolBar = FHComposeToolBar(frame: CGRectZero)

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpUI()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    // MARK: - 设置 ui
    
    private func setUpUI() {
    
        setNavUi()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectEmoticon:", name: DidSeletedEmotionButtonNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectDeleteEmoticon", name: DidSelecteDeleteEmoticonButtonNotification, object: nil)
        
        
        
        
        
        
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        textView.addSubview(pictureView)
        
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view).offset(UIEdgeInsetsZero)
        }
        
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(self.view)
            
            make.leading.equalTo(self.view)
            
            make.height.equalTo(30)
            
            make.bottom.equalTo(view)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            
            make.leading.equalTo(textView).offset(10)
            
            make.width.equalTo(textView).offset(-20)
            
            make.height.equalTo(textView.snp_width).offset(-20)
            
        }
        
        
        composeToolBar.composeToolBarCellBack = { [ weak self] (buttontype: FHComposeToolBarButtonType) in
        

            
            switch buttontype {
                
            case .Picture:
            self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("话题")
            case .Emoticon:
                self?.didSelectedemiticon()
                
            case .Add:
                print("加号")
                
                
            }
            
            
            
        }
        
        /**
        *  执行添加
        */
        self.pictureView.addButtonClosure = { [weak self] in
            
            self?.didSelectedPicture()
           
        }
        
    
    }
    
    private func setNavUi() {
    
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleLabel
        
    }
    
    // MARK: - toolbar  点击操作
    
    /**
     选择图片
     */
    private func didSelectedPicture() {
    
        
        let pickImage = UIImagePickerController()
        
        pickImage.delegate = self
        
        
        
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
        
            pickImage.sourceType = .Camera
            print("支持相机")
        } else {
        
            pickImage.sourceType = .PhotoLibrary
            print("不支持相机")
        }
        
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
        
            print("支持前置摄像头")
        
        }else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
        
            print("支持后置摄像头")
        }else {
        
            print("不支持摄像头")
        }
        
        presentViewController(pickImage, animated: true, completion: nil)
        
    
    }
    
    /**
     设置表情键盘
     */
    private func didSelectedemiticon() {
    
        if textView.inputView == nil {
        
            textView.inputView = keyBoard
        } else {
        
            textView.inputView = nil
        }
        //键盘图标显示
        composeToolBar.showEmotionIcon(textView.inputView != nil)
        
        textView.becomeFirstResponder()
        //键盘视图刷新
        textView.reloadInputViews()
        
    
    
    }
    

    
    // MARK: - 点击事件
    
    @objc private func cancelAction() {
        
        self.view.endEditing(true)
    
        dismissViewControllerAnimated(true, completion: nil)
    
    }

    
    @objc private func sendAction() {
        
        SVProgressHUD.show()
        
        let textString = textView.emoticonString!
        
        print(textString)
        
        
        if pictureView.imageArray.count == 0 {
        
            FHNetTools.shearedNetTools.update(textString) { (response, error) -> () in
                
                if error != nil {
                    
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    
                    return
                }
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
                
            }
        } else {
        
            FHNetTools.shearedNetTools.upload(pictureView.imageArray[0], status: textString, cellBack: { (response, error) -> () in
               
                if error != nil {
                    
                    SVProgressHUD.showErrorWithStatus("发送失败")
                    
                    return
                }
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
            })
        
        }
    
       
        
    }
    
    // MARK: - 接收通知
    
    /**
     键盘通知执行函数
     
     - parameter noti: <#noti description#>
     */
    @objc private func keyboardChangeFrame(noti: NSNotification) {
    
        // 屏幕frame
        let keyBoardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 动画时长
        
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber ).doubleValue
    
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - ScreenHeight)
            
        }
        
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    /**
     选择emoji 通知
     
     - parameter noti: <#noti description#>
     */
    
    @objc private func selectEmoticon(noti: NSNotification) {
    

        let emoticon = noti.object as! FHEmoticon
        
        textView.insertEmoticon(emoticon)

        
        
    }
    
    
    @objc private func selectDeleteEmoticon() {
    
       
        
        textView.deleteBackward()
        
    
    }
    
    
    
    
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}




// MARK: - UIImagePickerControllerDelegate

extension FHComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {

  
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        pictureView.hidden = false
        
        let scaleImage = scaleImageWithScaleWidth(200, image: image)
        

        pictureView.addImage(scaleImage)
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    /**
     根据指定压缩后的宽度,压缩图片
     
     - parameter width: 压缩的宽度
     - parameter image: 需要压缩的图片
     
     - returns:   压缩后的图片
     */
    private func scaleImageWithScaleWidth(scaleWidth: CGFloat, image: UIImage) -> UIImage {
    
    
        let scaleHeight = scaleWidth / image.size.width * image.size.height

        let size = CGSize(width: scaleWidth, height: scaleHeight)
        
        UIGraphicsBeginImageContext(size)
        
        
        image.drawInRect(CGRect(origin: CGPointZero, size: size))
        
        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
        
        
        UIGraphicsEndImageContext()
    
    
        return scaleImage
    
    }
    
    
}



// MARK: - textView 代理方法
extension FHComposeViewController: UITextViewDelegate {


    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
    
        self.view.endEditing(true)
    }
    

}



